﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data;

namespace DAO
{
    public class DataProvider
    {
        protected string constr;
        protected OleDbConnection conn;
        protected OleDbDataAdapter da = null;
        protected OleDbCommand cmd;

        public DataProvider()
        {
            constr = "Provider = Microsoft.Jet.OleDb.4.0;Data Source=..\\QUANLYNHANVIEN.mdb";
        }

        public void Connect()
        {
            try
            {
                conn = new OleDbConnection(constr);
                conn.Open();
            }
            catch (Exception ex)
            {
                throw new Exception("Loi khi thuc thi lenh SQL: " + ex.Message);
            }
        }

        public void disconnect()
        {
            try
            {
                conn.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("Loi khi thuc thi lenh SQL: " + ex.Message);
            }
        }

        public DataTable executeQuery(String sql)
        {
            Connect();
            DataSet ds = new DataSet();
            da = new OleDbDataAdapter(sql, conn);
            da.Fill(ds);
            disconnect();
            return ds.Tables[0];
        }
        //Dung cho cac thao tac insert, delete, update
        public void ExecuteNonQuery(string sql)
        {
            try
            {
                Connect();
                cmd = new OleDbCommand(sql, conn);
                cmd.ExecuteNonQuery();
                disconnect();
            }
            catch (Exception ex)
            {
                throw new Exception("Loi khi thuc thi lenh SQL: " + ex.Message);
            }
        }
        //Lay 1 gia tri du lieu ra
        public object executeScalar(string sql)
        {
            Connect();
            cmd = new OleDbCommand(sql, conn);
            object o = cmd.ExecuteScalar();
            disconnect();
            return o;
        }
        public string ConnectionString
        {
            get
            {
                return constr;
            }
            set
            {
                constr = value;
            }
        }
    }
}
